package com.example.userpage.service;

import com.example.userpage.model.UserInfoDto;
import com.example.userpage.model.ImageVote;
import com.example.userpage.repository.UserMessageRepository;
import com.example.userpage.repository.UserVotesRepository;
import com.example.userpage.repository.ImageVotesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserPageService {
    @Autowired private UserMessageRepository msgRepo;
    @Autowired private UserVotesRepository votesRepo;
    @Autowired private ImageVotesRepository imagesRepo;

    public UserInfoDto getUserInfo(String ip) {
        Map<String,Object> user = msgRepo.findByIp(ip);
        String username    = (String) user.get("username");
        String createdTime = user.get("createdTime").toString();

        // 构造图片接口 URL，前端会发 GET 请求来获取原始二进制
        String picUrl = "/userpage/avatar?ip=" + ip;

        Map<String,Object> vote = votesRepo.findByUsername(ip);
        String vote_time = vote.get("vote_time").toString();
        int    vote_num  = (Integer) vote.get("vote_num");

        List<ImageVote> list = imagesRepo.findByCreatorOrderByVotes(username);
        int n = list.size();
        Map<String,Object> extra = new HashMap<>();
        for (int i = 0; i < n; i++) {
            extra.put("name_" + (i+1),          list.get(i).getImage_name());
            extra.put("currentVotes_" + (i+1), list.get(i).getVote_count());
        }

        UserInfoDto dto = new UserInfoDto();
        dto.setUsername(username);
        dto.setCreatedTime(createdTime);
        dto.setPicUrl(picUrl);
        dto.setVote_time(vote_time);
        dto.setVote_num(vote_num);
        dto.setCharacterNum(n);
        dto.setExtra(extra);
        return dto;
    }
}
